import roleApi from '@/api/system/role'
import menuApi from '@/api/system/menu'

export default {
  name: 'role',
  data() {
    return {
      formVisible: false,
      formTitle: '添加角色',

      roleList: [],
      isAdd: true,
      checkedPermissionKeys: [],
      isCheck: true,
      permissons: [],
      defaultProps: {
        id: 'id',
        label: 'name',
        children: 'children'
      },
      permissonVisible: false,
      form: {
        code: '',
        name: '',
        id: '',
        version: '',
        pName: '',
        num: 1
      },
      rules: {
        code: [
          {required: true, message: '请输入角色编码', trigger: 'blur'},
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ]
      },
      listQuery: {
        current: 1,
        size: 20,
        criteria:{
          name: undefined,
          code: undefined
        }
      },
      total: 0,
      list: null,
      listLoading: true,
      selRow: {},
      noticeTypeList:[],
      noticeVisible:false,
      checkAll: false,
        checkedCities: [],
        cities: [],
        isIndeterminate: true,
        roleId:''
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.fetchData()
      this.getNoticeType()
    },
    fetchData() {
      this.listLoading = true
      roleApi.getList(this.listQuery).then(response => {
        this.list = response.data.records
        this.listLoading = false
        this.total = response.data.total
      })
    },
    search() {
      this.listQuery.current = 1
      this.fetchData()
    },
    reset() {
      this.listQuery.criteria.name = ''
      this.listQuery.current = 1
      this.listQuery.criteria.code = ''
      this.fetchData()
    },
    fetchPage(page) {
          this.listQuery.current = page
          this.fetchData()
        },
    handleFilter() {
      this.getList()
    },
    fetchNext() {
      this.listQuery.current = this.listQuery.current + 1
      this.fetchData()
    },
    fetchPrev() {
      this.listQuery.current = this.listQuery.current - 1
      this.fetchData()
    },
    fetchcurrent(current) {
      this.listQuery.current = current
      this.fetchData()
    },
    changeSize(size) {
      this.listQuery.size = size
      this.fetchData()
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.selRow = currentRow
    },
    resetForm() {
      this.form = {
        code: '',
        name: '',
        id: '',
        version: '',
        pName: '',
        num: 1
      }
    },
    add() {
      this.resetForm()
      this.formTitle = '添加角色'
      this.formVisible = true
      this.isAdd = true
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          roleApi.save({
            id: this.form.id,
            num: this.form.num,
            name: this.form.name,
            code: this.form.code
          }).then(response => {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.fetchData()
            this.formVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    checkSel() {
      if (this.selRow && this.selRow.id) {
        return true
      }
      this.$message({
        message: '请选中操作项',
        type: 'warning'
      })
      return false
    },
    editItem(record) {
      this.selRow = Object.assign({}, record);
      this.edit()
    },
    edit() {
      if (this.checkSel()) {
        this.isAdd = false
        this.form = this.selRow
        this.form.status = this.selRow.statusName === '启用'
        this.form.password = ''
        this.formTitle = '修改角色'
        this.formVisible = true
      }
    },
    removeItem(record) {
      this.selRow = record
      this.remove()
    },
    remove() {
      if (this.checkSel()) {
        const id = this.selRow.id
        this.$confirm('确定删除该记录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          roleApi.remove(id).then(response => {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.fetchData()
          })
        }).catch(() => {
        })
      }
    },
    openPermissionsItem(record) {
      this.selRow = record
      this.openPermissions()
    },
    openPermissions() {
      if (this.checkSel()) {
        menuApi.menuTreeListByRoleId(this.selRow.id).then(response => {
          //关闭级联效果
          this.isCheck = true

          this.$nextTick(() => {
          this.permissons = response.data.treeData
          this.checkedPermissionKeys = response.data.checkedKeys
          //再打开级联效果
            this.isCheck = false;
          });
          this.permissonVisible = true
        })
      }
    },
    savePermissions() {
      let checkedNodes = this.$refs.permissonTree.getCheckedNodes(false, true)
      let menuIds = []
      for (const index in checkedNodes) {
        menuIds.push( checkedNodes[index].id)
      }
      const data = {
        roleId: this.selRow.id,
        permissionIds: menuIds
      }
      roleApi.savePermissons(data).then(response => {
        this.permissonVisible = false
        this.$message({
          message: '提交成功',
          type: 'success'
        })
      })
    },
    openNotice(id){
      if(!id){
        return
      }
      //获取角色拥有的通知类型
      roleApi.getRoleNotice(id).then(response=>{
        const data = response.data
        let array = []
        if(data){
          for (let item of data) {
            // item指的的就是数组每一项的值
            array.push(item.noticeCode)
          }
        }
        this.checkedCities = array
        this.roleId = id

        this.noticeVisible = true
      })

    },
    getNoticeType(){
      roleApi.getNoticeType().then(response=>{
        this.noticeTypeList = response.data
        let array = []
        if( this.noticeTypeList){
          for (let item of  this.noticeTypeList) {
            // item指的的就是数组每一项的值
            array.push(item.code)
          }
        }
        this.cities = array
      })
    },
    getNoticeName(code){
      for (let item of  this.noticeTypeList) {
        if(code == item.code){
          return item.type
        }
      }
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    saveNotice(){
      if(!this.roleId){
        this.$message({
          message: '请选中操作项',
          type: 'warning'
        })
      }
      let from ={
        noticeCodes:this.checkedCities
      }
      roleApi.saveNotice(this.roleId,this.checkedCities).then(response =>{
        this.$message({
          message: '提交成功',
          type: 'success'
        })
        this.noticeVisible = false
      })
      
    }
  }
}
